import React, { memo, useRef, useState } from 'react';
import { isFunction } from 'lodash';
import {
  List,
  ListItem,
  ListItemAvatar,
  Avatar,
  ListItemText,
  Typography,
  Divider,
  CardHeader,
  IconButton,
  Card,
  TextField,
  makeStyles,
  CircularProgress,
  Box,
  Button,
  Dialog,
  DialogTitle,
  DialogActions,
  DialogContent,
} from '@material-ui/core';
import SendIcon from '@material-ui/icons/Send';
import ChatBubbleOutlineIcon from '@material-ui/icons/ChatBubbleOutline';
import { useHistory } from 'react-router-dom';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
    // backgroundColor: theme.palette.background.paper,
  },
  inline: {
    display: 'inline',
  },
  comment: {
    marginTop: theme.spacing(2),
  },
  commentCardHeaderAction: {
    margin: 0,
  },
  commentChildrenContainer: {
    backgroundColor: 'rgba(0,0,0,0.03)',
    padding: theme.spacing(1, 1),
    marginBottom: theme.spacing(1),
  },
  sendCommentIconButton: {
    width: 50,
    height: 50,
  },
  commentInput: {
    width: '98%',
  },
  timeAndAction: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
}));

const Comment = (props) => {
  const {
    user,
    comment,
    comments,
    sendingComment,
    onCommentInputChange,
    onSendComment,
    onSendCommentReply,
  } = props;

  const classes = useStyles();
  const history = useHistory();
  const parentKey = useRef();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [commentReply, setCommentReply] = useState('');

  const handleCommentInputChange = (e) => {
    if (isFunction(onCommentInputChange)) {
      onCommentInputChange(e.target.value);
    }
  };

  const handleSendComment = async () => {
    if (isFunction(onSendComment)) {
      await onSendComment();
    }
  };

  const handleCommentReplyClick = (key) => {
    parentKey.current = key;
    setDialogOpen(true);
  };

  const handleDialogClose = () => {
    setDialogOpen(false);
  };

  const handleSendCommentReply = async () => {
    if (isFunction(onSendCommentReply)) {
      await onSendCommentReply(parentKey.current, commentReply);
    }
    setDialogOpen(false);
    setCommentReply('');
  };

  const handleCommentReplyInputChange = (e) => {
    setCommentReply(e.target.value);
  };

  const handleCommentInputFocus = () => {
    if (user) return;
    history.push('/signIn');
  };

  return (
    <>
      <Card className={classes.comment}>
        <CardHeader
          classes={{ action: classes.commentCardHeaderAction }}
          avatar={user ? <Avatar>{user.name}</Avatar> : <Avatar />}
          action={(
            <IconButton
              onClick={handleSendComment}
              aria-label="send"
              color="primary"
              className={classes.sendCommentIconButton}
            >
              {sendingComment ? <CircularProgress size={20} /> : <SendIcon />}
            </IconButton>
          )}
          title={(
            <TextField
              size="small"
              onFocus={handleCommentInputFocus}
              className={classes.commentInput}
              multiline
              label="评论..."
              variant="outlined"
              value={comment}
              onChange={handleCommentInputChange}
            />
          )}
        />
        <List className={classes.root}>
          {comments.map((item, i) => (
            <Box key={item.key}>
              <ListItem alignItems="flex-start">
                <ListItemAvatar>
                  {item.name ? (
                    <Avatar>{item.name.slice(0, 1)}</Avatar>
                  ) : (
                    <Avatar />
                  )}
                </ListItemAvatar>
                <ListItemText
                  primary={item.name}
                  secondaryTypographyProps={{
                    component: 'div',
                  }}
                  secondary={(
                    <>
                      <Typography
                        component="span"
                        variant="body2"
                        className={classes.inline}
                        color="textPrimary"
                      >
                        {item.content}
                      </Typography>
                      <Box className={classes.timeAndAction}>
                        {item.createTime}
                        <Button
                          variant="contained"
                          color="primary"
                          size="small"
                          startIcon={<ChatBubbleOutlineIcon />}
                          onClick={() => handleCommentReplyClick(item.key)}
                        >
                          回复
                        </Button>
                      </Box>
                      {Array.isArray(item.children) && (
                        <Box>
                          {item.children.map((c) => (
                            <ListItem key={c.key} alignItems="flex-start" component="div">
                              <ListItemAvatar>
                                {c.name ? (
                                  <Avatar>{c.name.slice(0, 1)}</Avatar>
                                ) : (
                                  <Avatar />
                                )}
                              </ListItemAvatar>
                              <ListItemText
                                primary={c.name}
                                secondaryTypographyProps={{
                                  component: 'div',
                                }}
                                secondary={(
                                  <>
                                    <Box
                                      className={
                                        classes.commentChildrenContainer
                                      }
                                    >
                                      <Typography
                                        component="span"
                                        variant="body2"
                                        className={classes.inline}
                                        color="textPrimary"
                                      >
                                        {`回复:${c.parent.name}`}
                                        <br />
                                        {c.parent.content}
                                      </Typography>
                                    </Box>
                                    <Typography
                                      component="span"
                                      variant="body2"
                                      className={classes.inline}
                                      color="textPrimary"
                                    >
                                      {c.content}
                                    </Typography>
                                    <Box className={classes.timeAndAction}>
                                      {c.createTime}
                                      <Button
                                        variant="text"
                                        color="primary"
                                        size="small"
                                        startIcon={<ChatBubbleOutlineIcon />}
                                        onClick={() => handleCommentReplyClick(c.key)}
                                      >
                                        回复
                                      </Button>
                                    </Box>
                                  </>
                                )}
                              />
                            </ListItem>
                          ))}
                        </Box>
                      )}
                    </>
                  )}
                />
              </ListItem>
              {comments.length !== i + 1 && (
                <Divider variant="inset" component="li" />
              )}
            </Box>
          ))}
        </List>
      </Card>
      <Dialog
        open={dialogOpen}
        onClose={handleDialogClose}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">回复</DialogTitle>
        <DialogContent>
          <TextField
            style={{ width: 500 }}
            autoFocus
            margin="dense"
            multiline
            id="name"
            label="回复"
            value={commentReply}
            onChange={handleCommentReplyInputChange}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDialogClose} size="small" color="primary">
            取消
          </Button>
          <Button
            onClick={handleSendCommentReply}
            size="small"
            color="primary"
            variant="contained"
          >
            发送
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default memo(Comment);
